from typing import Optional
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import uvicorn

# 创建app对象
app = FastAPI()


# 创建数据模型
class Book(BaseModel):
    title: str
    author: str
    price: float
    description: Optional[str] = "这是一本好书。"


# 测试数据
books_db = [
    {"id": 1, "title": "看漫画学Python", "author": "关东升", "price": 29.99},
    {"id": 2, "title": "杀死一只知更鸟", "author": "Harper Lee", "price": 19.99},
    {"id": 3, "title": "Python从小白到大牛", "author": "关东升", "price": 49.99},
    {"id": 4, "title": "漫画Java", "author": "关东升", "price": 39.99},
]


# 路由函数
@app.put("/books/{book_id}")
def update_book(book_id: int, book: Book):
    for item in books_db:
        if item["id"] == book_id:
            item.update(book.dict())
            return {"message": f"Book {book_id} 更新成功"}

    # 没有找到要更新Book数据
    raise HTTPException(status_code=404, detail="没有找到要更新Book数据")


if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)
